package userinterface;

import interfacemanagement.MainWindowManager;
import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import config.ConfigManager;

public class TrayWindow {
	private TrayIcon trayIcon;
	private MainWindowManager manager;
	private MenuItem aboutItem;
	private MenuItem configItem;
	private MenuItem startItem;
	private MenuItem stopItem;
	private MenuItem exitItem;
	private PopupMenu popup;
	private SystemTray tray;
	private String basePath;

	private static TrayWindow instance;

	public static TrayWindow getInstance() {
		if (instance == null)
			instance = new TrayWindow();
		return instance;
	}

	private TrayWindow() {
	}

	public void createAndShowGUI() {
		createAndShowGUI(null);
	}

	public void createAndShowGUI(String path) {
		basePath = path;
		ConfigManager.setBasePath(basePath);
		// Check the SystemTray support
		if (!SystemTray.isSupported()) {
			System.out.println("SystemTray is not supported");
			return;
		}
		popup = new PopupMenu();
		trayIcon = new TrayIcon(createImage("/images/Network_small.png", "tray icon"));
		tray = SystemTray.getSystemTray();
		// Create a popup menu components
		aboutItem = new MenuItem("About");
		configItem = new MenuItem("Configuration");
		startItem = new MenuItem("Start");
		stopItem = new MenuItem("Stop");
		stopItem.setEnabled(false);
		exitItem = new MenuItem("Exit");
		// CheckboxMenuItem cb1 = new CheckboxMenuItem("Set auto size");
		// CheckboxMenuItem cb2 = new CheckboxMenuItem("Set tooltip");
		// Add components to popup menu
		popup.add(startItem);
		popup.add(stopItem);
		popup.addSeparator();
		popup.add(configItem);
		popup.add(aboutItem);
		popup.addSeparator();
		popup.add(exitItem);
		trayIcon.setPopupMenu(popup);
		trayIcon.setImageAutoSize(true);
		trayIcon.setToolTip("Hawar Indexer");
		try {
			tray.add(trayIcon);
		} catch (AWTException e) {
			e.printStackTrace();
			System.out.println("TrayIcon could not be added.");
			return;
		}
		trayIcon.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog(null, "This dialog box is run from System Tray");
			}
		});
		startItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					initializeManager();
				} catch (Exception e1) {
					e1.printStackTrace();
					System.exit(1);
				}
				manager.initializeFileProcessing();
			}
		});
		stopItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				trayIcon.displayMessage("Sun TrayIcon Demo", "Stop message", TrayIcon.MessageType.NONE);
			}
		});
		configItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				new ConfigurationWindow().setVisible(true);
			}
		});
		aboutItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				new AboutWindow().setVisible(true);
			}
		});
		exitItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				tray.remove(trayIcon);
				System.exit(0);
			}
		});
	}

	// Obtain the image URL
	protected Image createImage(String path, String description) {
		URL imageURL = null;
		String fullPath = "";
		try {
			if (basePath != null && !basePath.equals("")) {
				fullPath = basePath.substring(0, basePath.length() - 1) + path;
				imageURL = new URL(fullPath);
			} else {
				fullPath = path;
				imageURL = TrayIcon.class.getResource(fullPath);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			System.out.println("Malformed URL: " + ex.getMessage());
		}
		if (imageURL == null) {
			System.err.println("Resource not found: " + fullPath);
			return null;
		} else {
			return (new ImageIcon(imageURL, description)).getImage();
		}
	}

	private void initializeManager() {
		try {
			this.startItem.setEnabled(false);
			this.configItem.setEnabled(false);
			this.stopItem.setEnabled(true);
			manager = new MainWindowManager(this, "");
			// manager.initializeFileProcessing();
		} catch (ClassNotFoundException ex) {
			ex.printStackTrace();
			System.out.println("initializeManager exception: " + ex.getMessage());
		} catch (IOException ex) {
			ex.printStackTrace();
			System.out.println("initializeManager exception: " + ex.getMessage());
		}
	}

	public void notifySuccessfullyFinalization(String message) {
		trayIcon.displayMessage(message, "Finalization Message", TrayIcon.MessageType.INFO);
		this.startItem.setEnabled(true);
		this.stopItem.setEnabled(false);
		this.configItem.setEnabled(true);
	}

	public void notifyOnError(String message) {
		trayIcon.displayMessage(message, "Finalization Message", TrayIcon.MessageType.ERROR);
		this.startItem.setEnabled(true);
		this.stopItem.setEnabled(false);
	}

	public void notifyAdvance(long advanceDirAmount, long totalDirs, long advanceFileAmount, long totalFiles) {
		String toolTip = "Hawar Indexer: indexando directorio "
				+ advanceDirAmount + " de " + totalDirs 
				+ "\n - Archivo " 
				+ advanceFileAmount + " de " + totalFiles;
		trayIcon.setToolTip(toolTip);
	}
}
